<?php
// 开启session（会话）
session_start();
//首先读取前端传输过来的用户输入的内容
$username = trim($_POST['username']);
$pw = trim($_POST['pw']);
if($username == '' or $pw == ''){
    echo "<script>alert('用户名和密码都必须要填写！');history.back();</script>";
    exit;
}
$code = $_POST['code'];
//接下来判断验证码是否正确
/*echo strtolower($code);
echo strtolower($_SESSION["captcha"]);
exit;*/
if(strtolower($code) <> strtolower($_SESSION["captcha"])){  //说明验证码错误
    echo "<script>alert('验证码错误！');history.back();</script>";
    exit;
}
//$pw = md5($pw);
//接下来，在数据库中进行查找用户输入的用户名和密码。找到了，登录成功。找不到，登录失败
include "conn.php";
$sql = "select * from userinfo where username = '$username' and pw = '" . md5($pw) . "'";
$result = mysqli_query($conn,$sql);
$num = mysqli_num_rows($result);
if($num){ //登录成功
    //将登录日志写入数据表
    $info = mysqli_fetch_array($result);
    //$sql = "insert into log (userid,loggeddate) VALUE ('".$info['id']."','".time()."')";
    //$result = mysqli_query($conn,$sql);
    /*echo $sql;
    echo mysqli_error($conn);
    exit;*/
    /*if(!$result){
        echo "<script>alert('登录日志写入失败！');</script>";
    }*/
    if($info['admin'] == 1){ //说明当前登录者是管理员
        echo "<script>alert('恭喜你，登录成功！');location.href='index.php';</script>";
        $_SESSION['admin'] = 1; //管理员登录的标志
    }
    else{
        echo "<script>alert('恭喜你，登录成功！');location.href='index.php';</script>";
        $_SESSION['admin'] = '';
    }
    $_SESSION['loggedUsername'] = $username;
}
else{
    echo "<script>alert('对不起，登录失败！');history.back();</script>";
    $_SESSION['loggedUsername'] = '';
    $_SESSION['admin'] = '';
}
?>